package com.yz.xyt.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yz.xyt.constant.Constants;
import com.yz.xyt.constant.HttpStatus;
import com.yz.xyt.domain.ResponseResult;
import com.yz.xyt.domain.Student;
import com.yz.xyt.domain.User;
import com.yz.xyt.domain.vo.StudentImportVo;
import com.yz.xyt.domain.vo.StudentVo;
import com.yz.xyt.mapper.StudentMapper;
import com.yz.xyt.service.*;
import com.yz.xyt.utils.DateUtils;
import com.yz.xyt.utils.RegexUtils;
import com.yz.xyt.utils.SecurityUtils;
import org.apache.commons.collections4.ListUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class StudentServiceImpl implements IStudentService {

    @Autowired
    StudentMapper studentMapper;

    @Autowired
    IUserService userService;

    @Autowired
    IRoleService roleService;

    @Autowired
    IClazzService clazzService;


    @Override
    public int deleteByPrimaryKey(Integer sid) {
        return studentMapper.deleteByPrimaryKey(sid);
    }

    @Transactional
    @Override
    public int insert(Student record) {
        return studentMapper.insert(record);
    }

    @Transactional
    @Override
    public int insertSelective(Student record) {
        return studentMapper.insertSelective(record);
    }

    @Override
    public Student selectByPrimaryKey(Integer sid) {
        return studentMapper.selectByPrimaryKey(sid);
    }

    @Transactional
    @Override
    public int updateByPrimaryKeySelective(Student record) {
        return studentMapper.updateByPrimaryKeySelective(record);
    }

    @Transactional
    @Override
    public int updateByPrimaryKey(Student record) {
        return studentMapper.updateByPrimaryKey(record);
    }

    @Transactional
    @Override
    public int updateByStudentNumberSelective(Student record) {
        return studentMapper.updateByStudentNumberSelective(record);
    }

    @Override
    public Student findByStudentNumber(String studentNumber) {
        return studentMapper.findByStudentNumber(studentNumber);
    }

    @Transactional
    public void syncAddStudent(List<Student> lists){
        List<List<Student>> partition = ListUtils.partition(lists, 100);
        for (List<Student> list : partition){
            //过滤重复数据
            List<Student> studentList = new ArrayList<>();
            list.stream().forEach(student -> {
                Student record = findByStudentNumber(student.getStudentNumber());
                if(record == null){
                    studentList.add(student);
                }
            });
            //新增学生信息
            studentList.stream().peek(student -> {
                student.setCreateBy(SecurityUtils.getUsername());
                student.setCreateDate(DateUtils.getNowDate());
            }).collect(Collectors.toList()).stream().forEach(this::insertSelective);

            //创建系统用户
            List<User> accountList = new ArrayList<>();
            studentList.stream().forEach(student -> {
                User user = new User();
                user.setUserName(student.getStudentNumber());
//                if(StringUtils.isEmpty(student.getPhone())){
//                    user.setPassword(Constants.DEFAULT_PASSWORD);
//                }else{
//                    String phone = student.getPhone();
//                    //验证是否是手机号
//                    boolean isPhone = RegexUtils.checkMobile(phone);
//                    if(!isPhone){
//                        user.setPassword(Constants.DEFAULT_PASSWORD);
//                    }else{
//                        user.setPassword(student.getPhone().substring(student.getPhone().length()-6));
//                    }
//                }
                user.setPassword(Constants.DEFAULT_PASSWORD);

                user.setPhone(student.getPhone());
                user.setAccountName(student.getName());
                user.setSex(student.getSex());
                user.setCreateBy(student.getCreateBy());
                user.setCreateDate(student.getCreateDate());
                //01	在读
                //02	休学
                //03	保留学籍
                //04	退学
                //05	注销学籍
                //06	放弃入学资格
                //07	保留入学资格
                //08	已毕业
                //09	结业
                //10	死亡
                if (student.getStatus().equals("01")) {
                    user.setStatus(Constants.ACCOUNT_ENABLE);
                }else{
                    user.setStatus(Constants.ACCOUNT_DISABLE);
                }
                accountList.add(user);
            });
            userService.createSystemAccount(accountList);
            //添加学生角色
            accountList.forEach(user -> {
                roleService.addUserRole(user.getId(),Long.valueOf(9));
            });
        }
    }

    /**
     * 同步更新学生
     * @param lists
     */
    @Transactional
    @Override
    public void syncUpdateStudent(List<Student> lists) {
        List<List<Student>> partition = ListUtils.partition(lists, 100);
        for (List<Student> list : partition){
            //更新学生信息
            list.stream().peek(student -> {
                student.setUpdateBy(SecurityUtils.getUsername());
                student.setUpdateDate(DateUtils.getNowDate());
            }).collect(Collectors.toList()).forEach(this::updateByStudentNumberSelective);

            //创建系统用户
            List<User> accountList = new ArrayList<>();
            list.stream().forEach(student -> {
                User user = new User();
                user.setUserName(student.getStudentNumber());
                //此处如果学生电话号码更改，不更系统用户新密码
                user.setAccountName(student.getName());
                user.setPhone(student.getPhone());
                user.setSex(student.getSex());
                user.setCreateBy(student.getCreateBy());
                user.setCreateDate(student.getCreateDate());

                if (student.getStatus().equals("01")) {
                    user.setStatus(Constants.ACCOUNT_ENABLE);
                }else{
                    user.setStatus(Constants.ACCOUNT_DISABLE);
                }
                accountList.add(user);
            });
            //更新系统账号信息
            accountList.stream().forEach(user -> {
                userService.updateByUserNameSelective(user);
            });
        }
    }

    /**
     * 同步删除
     * @param lists
     */
    @Transactional
    @Override
    public void syncDeleteStudent(List<Student> lists) {
        List<List<Student>> partition = ListUtils.partition(lists, 100);
        for (List<Student> list : partition) {
            list.stream().forEach(student -> {
                studentMapper.deleteByStudentNumber(student.getStudentNumber());
                userService.deleteByUserName(student.getStudentNumber());
            });
        }
    }

    /**
     * 查询学生列表
     * @param studentVo
     */
    @Override
    public PageInfo findStudentForPage(StudentVo studentVo) {
        //分页查询开始
        PageHelper.startPage(studentVo.getPageNumber(),studentVo.getPageSize());
        List<StudentVo> studentList = studentMapper.findStudentList(studentVo);
        return new PageInfo(studentList);
    }

    /**
     * 查询学生个人信息
     * @param studentNumber
     * @return
     */
    public StudentVo findStudentInfo(String studentNumber){
        return studentMapper.selectStudentInfo(studentNumber);
    }

    /**
     * 书记查询学生
     * @param studentVo
     * @return
     */
    @Override
    public PageInfo findBySjForPage(StudentVo studentVo) {
        //分页查询开始
        PageHelper.startPage(studentVo.getPageNumber(),studentVo.getPageSize());
        List<StudentVo> studentList = studentMapper.findBySjForPage(studentVo);
        return new PageInfo(studentList);
    }

    @Override
    public List<Student> convertStudent(List<StudentImportVo> studentList) {

        List<Student> list = new ArrayList<>();
        studentList.stream().forEach(s->{
            //查询班级编码
            String clazzNumber  =  clazzService.findClazzNumberByName(s.getClazzName());
            if (StringUtils.isNotEmpty(clazzNumber)){
                Student student = new Student();
                student.setName(s.getName());
                student.setSex(s.getSex());
                student.setClazzNumber(clazzNumber);
                student.setStudentNumber(s.getStudentNumber());
                student.setPhone(s.getPhone());
                student.setStatus("01");
                list.add(student);
            }
        });

        return list;
    }

    @Override
    public int deleteStudentByStudentNumber(String studentNumber) {
        return studentMapper.deleteByStudentNumber(studentNumber);
    }

    /**
     * 新增学生
     * @param student
     * @return
     */
    @Transactional
    public ResponseResult addStudent(Student student) {
        ResponseResult result = new ResponseResult();
        Student record = findByStudentNumber(student.getStudentNumber());
        if(null != record){
            result.setCode(HttpStatus.ERROR);
            result.setMsg("添加失败,该学生已存在");
        }else {
            student.setCreateBy(SecurityUtils.getUsername());
            student.setCreateDate(DateUtils.getNowDate());
            // 新增学生信息
            insertSelective(student);
            //创建系统用户
            User user = new User();
            user.setUserName(student.getStudentNumber());
            user.setPassword(SecurityUtils.encryptPassword(Constants.DEFAULT_PASSWORD));
            user.setPhone(student.getPhone());
            user.setAccountName(student.getName());
            user.setSex(student.getSex());
            user.setCreateBy(student.getCreateBy());
            user.setCreateDate(student.getCreateDate());
            user.setStatus(Constants.ACCOUNT_ENABLE);
            userService.insertSelective(user);
            //添加学生角色
            roleService.addUserRole(user.getId(), Long.valueOf(9));
            result.setCode(HttpStatus.SUCCESS);
            result.setMsg("添加学生成功");
        }
        return result;
    }

    /**
     * 更新学生信息
     * @param student
     * @return
     */
    @Transactional
    public ResponseResult updateStudent(Student student) {
        ResponseResult result =  new ResponseResult();
        student.setUpdateBy(SecurityUtils.getUsername());
        student.setUpdateDate(DateUtils.getNowDate());
        updateByPrimaryKeySelective(student);
        result.setMsg("修改学生成功");
        result.setCode(HttpStatus.SUCCESS);
        return result;
    }

    /**
     * 删除学生
     * @param student
     * @return
     */
    @Transactional
    public ResponseResult deleteStudent(Student student) {
        ResponseResult result = new ResponseResult();
        // 删除学生信息
        deleteStudentByStudentNumber(student.getStudentNumber());
        // 删除系统用户 studentNumber = userName
        User user = userService.findUser(student.getStudentNumber());
        userService.deleteByUserName(student.getStudentNumber());
        // 删除用户角色
        roleService.deleteUserRole(user.getId());
        result.setCode(HttpStatus.SUCCESS);
        result.setMsg("删除学生成功");
        return result;
    }

    /**
     * 查询学生列表
     * @param studentVo
     * @return
     */
    @Override
    public ResponseResult findStudentList(StudentVo studentVo) {
        ResponseResult result = new ResponseResult();
        List<StudentVo> studentList = studentMapper.findStudentList(studentVo);
        result.setCode(HttpStatus.SUCCESS);
        result.setMsg("查询学生列表成功");
        result.setData(studentList);
        return result;
    }

    /**
     * 获取学生完整信息列表
     * @param studentVo
     * @return
     */
    @Override
    public List<StudentVo> getStudents(StudentVo studentVo) {
        return studentMapper.findStudentList(studentVo);
    }
}
